package com.Khan.SocialRescueSys.controller;

import com.Khan.SocialRescueSys.pojo.*;
import com.Khan.SocialRescueSys.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Khan Liu
 * @date 2022/4/4 14:37
 */
@Controller
public class RepoController {

    @Autowired
    private ForceService forceService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private ProvinceService provinceService;

    @Autowired
    private MessageService messageService;

    @Autowired
    SendMail sendMail;

    @RequestMapping("/repo")
    public String toRepo(@RequestParam(required = false, defaultValue = "1", value = "pagenum") int pagenum, Model model) {

        PageHelper.startPage(pagenum, 4);
        List<Force> allForce = forceService.getIndexForce();
        /**获取博客的类型(联表查询)*/
        List<Type> allType = typeService.getForceType();
        /**获取博客的标签(联表查询)*/
        List<Province> allProvince = provinceService.getForceProvince();

        List<Message> indexSkill = messageService.getIndexSkill();

/*        List<ProvinceForceCount> provinceForceCount = forceService.getProvinceForceCount();
        for (ProvinceForceCount forceCount : provinceForceCount) {
            System.out.println(forceCount);
        }*/

        //得到分页结果对象
        PageInfo pageInfo = new PageInfo(allForce);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("provinces", allProvince);
        model.addAttribute("types", allType);
        model.addAttribute("skills", indexSkill);
        return "repo";
    }

    @GetMapping("/detail-skill/{id}")
    public String toSkillDetail(@PathVariable("id") Long id, Model model) {
        Message skill = messageService.getSkill(id);
        model.addAttribute("skill", skill);

        return "detail-skill";
    }

    @GetMapping("/detail/{id}")
    public String toForceDetail(@PathVariable("id") Long id, Model model) {
        Force force = forceService.getDetailedForce(id);
        force.setViews(force.getViews() + 1);
        forceService.updateForceView(id);
        model.addAttribute("force", force);
        model.addAttribute("email", new Email());
        return "detail";
    }

    @PostMapping("/sendEmail/{id}")
    public String sendEmail(@PathVariable("id") Long id, @ModelAttribute Email email, RedirectAttributes attributes) {
        String econtent = email.getEcontent();
        String ereceiver = email.getEreceiver();
//        SimpleMailMessage message = new SimpleMailMessage();
//        message.setFrom("2194510807@qq.com");
//        message.setText(econtent);
//        message.setSubject("Help");
//        message.setTo("2194510807@qq.com");
        try{
            if(econtent!=null && !econtent.equals("")){
                sendMail.sendSimpleMail(ereceiver,"社会救援力量信息管理统计系统代发",econtent);
            }else{
                attributes.addFlashAttribute("msg","邮件不可为空");
            }
        }catch (Exception e){
            e.printStackTrace();
            attributes.addFlashAttribute("msg","邮件发送失败");
        }


        return "redirect:/detail/" + id;
    }

    @PostMapping("/search")
    public String search(@RequestParam(required = false, defaultValue = "1", value = "pagenum") int pagenum, Model model,
                         @RequestParam String query) {
        PageHelper.startPage(pagenum, 100);
        List<Force> searchForces = forceService.getSearchForce(query);
        PageInfo<Force> pageInfo = new PageInfo<>(searchForces);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("query", query);
        return "search";
    }

    /**
     * 导出为Excel
     * */
    @RequestMapping(value = "UserExcelDownloads", method = RequestMethod.GET)
    public void downloadAllClassmate(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();//创建HSSFWorkbook对象,  excel的文档对象
        HSSFSheet sheet = workbook.createSheet("信息表"); //excel的表单

//        List<Teacher> classmateList = teacherservice.teacherinfor();
        List<Force> forceList = forceService.getIndexForce();

        String fileName = "info"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        String[] headers = { "标题","省份", "邮箱", "电话", "地址","详细内容"};
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Force force : forceList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(force.getTitle());
            row1.createCell(1).setCellValue(force.getProvince().getName());
            row1.createCell(2).setCellValue(force.getEmail());
            row1.createCell(3).setCellValue(force.getTel());
            row1.createCell(4).setCellValue(force.getAddr());
            row1.createCell(5).setCellValue(force.getContent());
            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
}
